/*
 * @Author: xiaosihan
 * @Date: 2023-12-07 23:48:21
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-12-08 00:40:10
 */

import { DesignTemplateDate, DesignTemplateGroup } from '#/type';
import templateManageService from '@/api/services/templateManageService';
import goodsUtils from '@/utils/goodsUtils';
import utils from '@/utils/utils';
import { get, TemplateExecutor } from 'lodash';
import { observable, configure, toJS } from 'mobx';

configure({ enforceActions: 'never' });

export interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

const templateListStore = observable({
  //全部组
  cascaderOptions: [] as Array<Option>,

  async getDesignTemplateGroup() {
    const res = (await templateManageService.getTemplateGroup()) as Array<DesignTemplateGroup>;

    const cascaderOptions: Array<Option> = res.map((g) => {
      return {
        value: g.id,
        label: g.name,
        children: g.sonList.map((s) => {
          return {
            value: s.id,
            label: s.name,
          };
        }),
      };
    });
    this.cascaderOptions = cascaderOptions;
    this.setActiveid([
      get(cascaderOptions, [0, 'value']) as number,
      get(cascaderOptions, [0, 'children', 0, 'value']) as number,
    ]);
  },

  // 当前选中的分组
  activeid: [0, 0],
  setActiveid(activeid: [number, number]) {
    this.activeid = activeid;
    this.page = 0;
    this.designTemplates = [];
    this.getNextPage();
  },

  //当前页
  page: 0,
  setCurrentPage(page: number) {
    this.page = page;
  },

  //搜索词
  searchValue: '',
  setSearchValue(searchValue: string) {
    this.searchValue = searchValue;
  },

  //加载状态
  loading: false,
  setLoading(loading: boolean) {
    this.loading = loading;
  },

  //是否有下一页
  hasNext: true,
  setHasNext(hasNext: boolean) {
    this.hasNext = hasNext;
  },

  //切换菜单 0 是模板列表 1是 收藏模板
  active: '0',
  setActive(active: '0' | '1') {
    this.active = active;
  },

  // 模板列表
  designTemplates: [] as Array<DesignTemplateDate>,
  setDesignTemplates(designTemplates: Array<DesignTemplateDate>) {
    this.designTemplates = designTemplates;
  },

  //获取下一页
  async getNextPage() {
    this.loading = true;
    this.page += 1;
    const res = await templateManageService
      .getTemplateList({
        pageNo: this.page,
        pageSize: 10,
        keyword: this.searchValue,
        groupId1: this.activeid[1],
      })
      .catch((err) => []);

    let list: Array<DesignTemplateDate> = get(res, ['list']) || [];
    list.map((l, i) => {
      l.designData = utils.JSONParse(l.designData as unknown as string);
    });
    this.hasNext = list.length === 10;
    this.setDesignTemplates([...toJS(this.designTemplates), ...list]);
    this.loading = false;
  },
});

templateListStore.getDesignTemplateGroup();

export default templateListStore;
